package cn.edu.dgut.sai;

import javax.servlet.AsyncContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Sai
 *
 * Java EE课程示例
 *
 * curl http://localhost:8080/test/newThreadAsync 或 在浏览器里输入网址，观察服务器的输出
 *
 * 注意servlet的线程名字与自定义的线程的名字的区别，自定义的线程不属于容器的http线程池
 */
@WebServlet(value = "/newThreadAsync", asyncSupported = true)
public class NewThreadAsyncHelloServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("手动创建线程的异步Servlet执行开始...");
        long start = System.currentTimeMillis();
        System.out.println("进入Servlet线程--" + Thread.currentThread().getName());

        AsyncContext asyncContext = request.startAsync();

        Runnable runnable = () -> {
            System.out.println("进入异步线程--" + Thread.currentThread().getName());

            new RunningProcessThread().run();

            try {
                response.setContentType("text/html;charset=UTF-8");
                asyncContext.getResponse().getWriter().println("手动创建线程的异步Servlet示例，Hello World!");
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 线程执行完成，响应客户端
            asyncContext.complete();

            System.out.println("退出异步线程--" + Thread.currentThread().getName());
        };

        // 自定义一个线程执行，不使用容器的http线程池
        new Thread(runnable).start();

        long end = System.currentTimeMillis();
        System.out.println("手动创建线程的异步Servlet执行完成，耗时：" + (end - start) + "毫秒");
        System.out.println("退出Servlet线程--" + Thread.currentThread().getName());
    }

}